﻿using System;
using System.Linq;
using Models;
using Prism.Commands;
using Prism.Regions;

namespace IntelligentParkingLot.ViewModels.Base
{
    public abstract class BaseViewModel : INavigationAware
    {
        /// <summary>
        /// 页面标题
        /// </summary>
        public string PageTitle { get; set; }

        /// <summary>
        /// 是否可以关闭页面
        /// </summary>
        public bool IsCanClose { get; set; } = true;

        /// <summary>
        /// 要关闭的页面名称
        /// </summary>
        private string pageName;

        /// <summary>
        ///  区域对象
        /// </summary>
        protected readonly IRegionManager regionManager;

        protected BaseViewModel(IRegionManager regionManager)
        {
            this.regionManager = regionManager;

            CloseCommand = new DelegateCommand(DoClose);
        }

        /// <summary>
        ///  关闭页面命令的实现
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void DoClose()
        {
            //拿到主区域，从区域里移除对应的页面，根据页面的名称
            var region = regionManager.Regions[RegionNameProvider.ContentRegion];
            var view = region.Views.FirstOrDefault(v => v.GetType().Name == pageName);
            if (view != null)
            {
                region.Remove(view);
            }
        }

        public DelegateCommand CloseCommand { get; set; }

        /// <summary>
        /// 页面导航事件
        /// </summary>
        /// <param name="navigationContext"> 导航上下文</param>
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            // 获取页面名称
            pageName = navigationContext.Uri.ToString();
        }

        /// <summary>
        /// 是否是导航目标
        /// </summary>
        /// <param name="navigationContext"> 导航上下文</param>
        /// <returns></returns>
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        /// <summary>
        ///  页面导航离开事件
        /// </summary>
        /// <param name="navigationContext"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnNavigatedFrom(NavigationContext navigationContext) { }
    }
}
